<?php
/***********************************************************
 * 静态生成
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller\channel;
use app\admin\controller\Base;
use think\facade\Db;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Cookie;
use app\common\logic\ArctypeLogic;
use think\paginator\driver; // 生成静态页面代码
class Seo extends Base
{
    public $popedom = '';
    public function initialize() {
        parent::initialize();
        $ctl_act = Request::controller().'/index';
        $this->popedom = appfile_popedom($ctl_act);
    }

    //配置入口
    public function index()
    { 
        //验证权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        $gzpcfglobal = get_global();
        // 纠正栏目的HTML目录路径字段值
        $this->correctArctypeDirpath();

        $inc_type = input('get.inc_type','seo');
        $this->assign('inc_type',$inc_type);
        $config = tpCache($inc_type);
        $config['seo_pseudo'] = tpCache('seo.seo_pseudo') ? tpCache('seo.seo_pseudo') : $gzpcfglobal['admin_config']['seo_pseudo'];
        if('seo' == $inc_type)
        {
            $seo_pseudo_list = get_seo_pseudo_list();
            $this->assign('seo_pseudo_list', $seo_pseudo_list);

            // 限制文档HTML保存路径的名称
            $wwwroot_dir = $gzpcfglobal['wwwroot_dir']; // 网站根目录的目录列表
            $disable_dirname = $gzpcfglobal['disable_dirname']; // 栏目伪静态时的路由路径
            $wwwroot_dir = array_merge($wwwroot_dir, $disable_dirname);

            // 不能与栏目的一级目录名称重复
            $arctypeDirnames = Db::name('arctype')->where(['parent_id'=>0])->column('dirname');
            is_array($arctypeDirnames) && $wwwroot_dir = array_merge($wwwroot_dir, $arctypeDirnames);
            $wwwroot_dir = array_unique($wwwroot_dir);
            $this->assign('seo_html_arcdir_limit', implode(',', $wwwroot_dir));

            $seo_html_arcdir_1 = '';
            if (!empty($gzpcfglobal['admin_config']['seo_html_arcdir'])) {
                $seo_html_arcdir = trim($gzpcfglobal['admin_config']['seo_html_arcdir'], '/');
                $seo_html_arcdir_1 = '/'.$seo_html_arcdir;
            }
            $this->assign('seo_html_arcdir_1', $seo_html_arcdir_1);

            // 标记是否第一次切换静态页面模式
            if (!isset($seo_html_arcdir)) {
                $init_html = 1; // 第一次切换
            } else {
                $init_html = 2; // 多次切换
            }
            $this->assign('init_html', $init_html);
        }
        else if ('html' == $inc_type)
        {
            $map = [];
            // 栏目列表
            $map[] = ['status','=',1];
            $map[] = ['is_del','=',0];
            $arctypeLogic = new ArctypeLogic();
            $select_html = $arctypeLogic->arctype_list(0,0,true,$gzpcfglobal['arctype_max_level'],$map);
            $this->assign('select_html',$select_html);
            // 允许发布文档列表的栏目
            $arc_select_html = allow_release_arctype();
            $this->assign('arc_select_html', $arc_select_html);
            // 生成完页面之后，清除缓存
            $this->buildhtml_clear_cache();
        }
        $this->assign('config',$config);//当前配置项
        return $this->fetch($inc_type);
    }

    // 新增修改配置（同步数据到其他语言里）
    public function handle()
    {
        //验证权限
        if(!$this->popedom["modify"]){
            if(config('params.auth_msg.test')){
                $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                return $result;
            }else{
                $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                return $result;                   
            }
        }
        $param = input('post.');
        $successData = [];
        $inc_type = $param['inc_type'];
        $globalConfig = tpCache('global');
        if ($inc_type == 'seo') {
            $seo_pseudo_new = $param['seo_pseudo'];
            
            // 生成静态页面代码
            unset($param['seo_html_arcdir_limit']);
            if (!empty($param['seo_html_arcdir']) && !preg_match('/^([0-9a-zA-Z\_\-\/]+)$/i', $param['seo_html_arcdir'])) {
                $result = ['status' => false, 'msg' => '页面保存路径的格式错误！'];
                return $result; 
            }
            if (!empty($param['seo_html_arcdir'])) {
                if (preg_match('/^([0-9a-zA-Z\_\-\/]+)$/i', $param['seo_html_arcdir'])) {
                    $param['seo_html_arcdir'] = '/'.trim($param['seo_html_arcdir'], '/');
                } else {
                    $result = ['status' => false, 'msg' => '页面保存路径的格式错误！'];
                    return $result; 
                }
            }
            $seo_html_arcdir_old = !empty($globalConfig['seo_html_arcdir']) ? $globalConfig['seo_html_arcdir'] : '';
            
            // 检测是否开启pathinfo模式
            try {
                if (3 == $seo_pseudo_new || (1 == $seo_pseudo_new && 2 == $param['seo_dynamic_format'])) {
                    $fix_pathinfo = ini_get('cgi.fix_pathinfo');
                    if (stristr($_SERVER['HTTP_HOST'], '.mylightsite.com')) {
                        $result = ['status' => false, 'msg' => '腾讯云空间不支持伪静态！'];
                        return $result; 
                    } else if ('' != $fix_pathinfo && 0 === $fix_pathinfo) {
                        $result = ['status' => false, 'msg' => '空间不支持伪静态，请开启pathinfo，或者在php.ini里修改cgi.fix_pathinfo=1'];
                        return $result;
                    }
                }
                // 生成静态页面代码 - URL模式切换时删掉根目录下的index.html静态文件
                if(1 == $seo_pseudo_new || 3 == $seo_pseudo_new){
                    if(file_exists('./index.html')){
                        @unlink('./index.html');
                    }
                }
            } catch (\Exception $e) {}

            // 强制去除index.php
            if (isset($param['seo_force_inlet'])) 
            {
                $seo_force_inlet = $param['seo_force_inlet'];
                $seo_force_inlet_old = !empty($globalConfig['seo_force_inlet']) ? $globalConfig['seo_force_inlet'] : '';
                if ($seo_force_inlet_old != $seo_force_inlet) {
                    $param['seo_inlet'] = $seo_force_inlet;
                }
            }
        }
        unset($param['inc_type']);
        tpCache($inc_type,$param);
        if ($inc_type == 'seo') {
            // 生成静态页面代码 - 更新分页php文件支持生成静态功能
            $this->update_paginatorfile();
            Cache::clear();
        } 
        $result = ['status' => true, 'msg' => '操作成功','data'=>$successData,'url'=>url('/channel.Seo/index',array('inc_type'=>$inc_type))->suffix(false)->domain(true)->build()];
        return $result;
    }

    // 纠正栏目的HTML目录路径字段值
    private function correctArctypeDirpath()
    {
        $system_correctArctypeDirpath = tpCache('system.system_correctArctypeDirpath');
        if (!empty($system_correctArctypeDirpath)) {
            return false;
        }
        $saveData = [];
        $arctypeList = Db::name('arctype')->order('grade asc')->column('id,parent_id,dirname,dirpath,grade','id');
        foreach ($arctypeList as $key => $val) {
            if (empty($val['parent_id'])) { // 一级栏目
                $saveData[] = [
                    'id'            => $val['id'],
                    'dirpath'       => '/'.$val['dirname'],
                    'grade'         => 0,
                    'update_time'   => getTime(),
                ];
            } else {
                $parentRow = $arctypeList[$val['parent_id']];
                if (empty($parentRow['parent_id'])) { // 二级栏目
                    $saveData[] = [
                        'id'            => $val['id'],
                        'dirpath'       => '/'.$parentRow['dirname'].'/'.$val['dirname'],
                        'grade'         => 1,
                        'update_time'   => getTime(),
                    ];
                } else { // 三级栏目
                    $topRow = $arctypeList[$parentRow['parent_id']];
                    $saveData[] = [
                        'id'            => $val['id'],
                        'dirpath'       => '/'.$topRow['dirname'].'/'.$parentRow['dirname'].'/'.$val['dirname'],
                        'grade'         => 2,
                        'update_time'   => getTime(),
                    ];
                }
            }
        }
        $r = Db::name('Arctype')->saveAll($saveData);
        if (false !== $r) {
            tpCache('system',['system_correctArctypeDirpath'=>1]);
        }
    }

    // 静态页面模式切换为其他模式时，检测之前生成的静态目录是否存在，并提示手工删除还是自动删除
    public function ajax_checkHtmlDirpath()
    {
        $result = ['status' => false,'msg' => '失败','data' => ''];
        $seo_pseudo_new = input('param.seo_pseudo_new/d');
        if (3 == $seo_pseudo_new) {
            $dirArr = [];
            $seo_html_listname = tpCache('seo.seo_html_listname');
            $row = Db::name('arctype')->field('dirpath')->select()->toArray();
            foreach ($row as $key => $val) {
                $dirpathArr = explode('/', $val['dirpath']);
                if (3 == $seo_html_listname) {
                    $dir = end($dirpathArr);
                } else {
                    $dir = !empty($dirpathArr[1]) ? $dirpathArr[1] : '';
                }
                if (!empty($dir) && !in_array($dir, $dirArr)) {
                    array_push($dirArr, $dir);
                }
            }
            $data = [];
            $data['msg'] = '';
            $num = 0;
            $wwwroot = glob('*', GLOB_ONLYDIR);
            foreach ($wwwroot as $key => $val) {
                if (in_array($val, $dirArr)) {
                    if (0 == $num) {
                        $data['msg'] .= "<font color='red'>根目录下有HTML静态目录，请先删除：</font><br/>";
                    }
                    $data['msg'] .= ($num+1)."、{$val}<br/>";
                    $num++;
                }
            }
            $data['height'] = $num * 24;
            $result['status'] = true;
            $result['msg']    = '检测成功！';
            $result['data'] = $data;
            return $result;
        }
    }

    // 自动删除静态HTML存放目录
    public function ajax_delHtmlDirpath()
    {
        $result = ['status' => false,'msg' => '失败','data' => ''];
        if (Request::isPost() || Request::isAjax()) {
            $error = false;
            $dirArr = [];
            $seo_html_listname = tpCache('seo.seo_html_listname');
            $row = Db::name('arctype')->field('dirpath')->select()->toArray();
            foreach ($row as $key => $val) {
                $dirpathArr = explode('/', $val['dirpath']);
                if (3 == $seo_html_listname) {
                    $dir = end($dirpathArr);
                } else {
                    $dir = !empty($dirpathArr[1]) ? $dirpathArr[1] : '';
                }
                $filepath = "./{$dir}";
                if (!empty($dir) && !in_array($dir, $dirArr) && file_exists($filepath)) {
                    @unlink($filepath."/index.html");
                    $bool = delFile($filepath, true);
                    if (false !== $bool) {
                        array_push($dirArr, $dir);
                    } else {
                        $error = true;
                    }
                }
            }
            $data = [];
            $data['msg'] = '';
            if ($error) {
                $num = 0;
                $wwwroot = glob('*', GLOB_ONLYDIR);
                foreach ($wwwroot as $key => $val) {
                    if (in_array($val, $dirArr)) {
                        if (0 == $num) {
                            $data['msg'] .= "<font color='red'>部分目录删除失败，请手工删除：</font><br/>";
                        }
                        $data['msg'] .= ($num+1)."、{$val}<br/>";
                        $num++;
                    }
                }
                $data['height'] = $num * 24;
                $result['status'] = false;
                $result['msg']    = '删除失败！';
                $result['data'] = $data;
                return $result;
            }
            $result['status'] = true;
            $result['msg']    = '删除成功！';
            $result['data'] = $data;
            return $result;
        }
    }

    // 生成完页面之后，清除缓存
    private function buildhtml_clear_cache()
    {
        // 文档参数缓存
        Cache::clear("article_info_serialize");
        Cache::clear("article_page_total_serialize");
        Cache::clear("article_content_serialize");
        Cache::clear("article_attr_info_serialize");
        Cache::clear("article_children_row_serialize");
        // 栏目参数缓存
        Cache::clear("channel_page_total_serialize");
        Cache::clear("channel_info_serialize");
        Cache::clear("has_children_Row_serialize");
    }



    // 生成总站
    public function site()
    {
        return $this->fetch();
    }

    // 生成栏目页
    public function channel()
    {
        $typeid = input('param.typeid/d','0'); // 栏目ID
        $this->assign("typeid",$typeid);
        return $this->fetch();
    }

    // 生成文档页
    public function article()
    {
        $typeid = input('param.typeid/d','0'); // 栏目ID
        $this->assign("typeid",$typeid);
        return $this->fetch();
    }


    // 生成静态页面代码 - 更新分页php文件支持生成静态功能
    private function update_paginatorfile()
    {
    }

    // 生成整站静态文件
    public function buildSite()
    {
    }

    // 获取生成栏目或文章的栏目id
    public function getAllType()
    {
    }



}
